//
//  TeachBottomView.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/10/15.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "TeachBottomView.h"
#import "TeachBottomCell.h"
#import "TeachSignerMessageController.h"
@interface TeachBottomView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UIButton *topSelectBtn;
@property (nonatomic,strong) UIButton *leftSelectBtn;
@property (nonatomic,strong) UIView *headerView;
@property (nonatomic,strong) UIImageView *noDataImgView;
@property (nonatomic,strong) NSMutableArray *topButtonsArr;
@property (nonatomic,copy) NSArray *dataArr;
@property (nonatomic,copy) NSArray *timeArr;
@property (nonatomic,copy) NSString *selectTime;
@property (nonatomic,assign) NSInteger selectSubject;

@end

@implementation TeachBottomView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubView];
    }
    return self;
}

#pragma mark ==========创建视图==========
- (void)createSubView{
    self.backgroundColor = [UIColor colorWithHexString:@"#eeeeee"];
    UIView *topView = [self returnTopView];
    _topView = topView;
    [self addSubview:self.topView];
    
    UIView *leftView = [self returnLeftBtn];
    _leftView = leftView;
    [self addSubview:self.leftView];
    
    [self addSubview:self.noDataImgView];
    
    [self addSubview:self.tableView];
    
    self.selectTime = [[[self.timeArr objectAtIndex:0] componentsSeparatedByString:@"\n"] firstObject];
    self.selectSubject = 2;

    //数据加载
    [self loadData];
}

#pragma mark ==========获取数据==========
- (void)loadData{
//    if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateAlertWithType:WithMessage:)]) {
//        [self.delegate teachBottomViewDelegateAlertWithType:1 WithMessage:nil];
//    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:self.selectTime forKey:@"currentDate"];
    [dic setValue:[NSNumber numberWithInteger:self.selectSubject] forKey:@"subjectType"];
    [[NetworkEngine sharedClient] GETByToken:TEACHFISTPAGEWITHSIGNLIST data:dic success:^(id responseObject) {
//        if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateAlertWithType:WithMessage:)]) {
//            [self.delegate teachBottomViewDelegateAlertWithType:2 WithMessage:nil];
//        }
        if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
            if ([[responseObject objectForKey:@"data"] count]!=0) {
                self.dataArr = [[[responseObject objectForKey:@"data"] objectAtIndex:0] objectForKey:@"schoolTimeList"];
            }
            if (self.noDataImgView.hidden) {
                if (self.dataArr.count==0) {
                    self.noDataImgView.hidden = NO;
                    self.tableView.hidden = YES;
                }
            } else {
                if (self.dataArr.count!=0) {
                    self.tableView.hidden = NO;
                    self.noDataImgView.hidden = YES;
                }
            }
            [self.tableView reloadData];
        } else if ([[responseObject objectForKey:@"code"] integerValue] == 2) {
            if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateToVCWithJudge:)]) {
                [self.delegate teachBottomViewDelegateToVCWithJudge:1];
            }
        }else {
            if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateAlertWithType:WithMessage:)]) {
                [self.delegate teachBottomViewDelegateAlertWithType:3 WithMessage:[responseObject objectForKey:@"msg"]];
            }
        }
    } failure:^(NSString *error) {
//        if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateAlertWithType:WithMessage:)]) {
//            [self.delegate teachBottomViewDelegateAlertWithType:2 WithMessage:nil];
//        }
    }];
}

#pragma mark ==========顶部视图==========
- (UIView *)returnTopView{//110*90
    //日历按钮宽度
    CGFloat calendarWidth = 90*SCALEUNIT;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20*SCALEUNIT, 20*SCALEUNIT, self.frame.size.width-20*2*SCALEUNIT, 90*SCALEUNIT)];
    view.backgroundColor = [UIColor whiteColor];
    UIScrollView *weekScrView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(view.frame)-calendarWidth, CGRectGetHeight(view.frame))];
    weekScrView.contentSize = CGSizeMake(170*SCALEUNIT*7, 90*SCALEUNIT);
    weekScrView.showsHorizontalScrollIndicator = NO;
    weekScrView.tag = 10000;
    [view addSubview:weekScrView];
    self.timeArr = [self getPriousorLaterDateFromDate:[NSDate date]];
    for (int i=0; i<7; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(170*SCALEUNIT*i, 0, 170*SCALEUNIT, 90*SCALEUNIT);
        [btn setTitle:[self.timeArr objectAtIndex:i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"#686868"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [btn.titleLabel setNumberOfLines:2];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:LoginFont-4]];
        btn.showsTouchWhenHighlighted=YES;
        btn.tag = 10000+i;
        [btn addTarget:self action:@selector(touchChange:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            [btn setBackgroundColor:[UIColor colorWithHexString:@"#21d4a4"]];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.topSelectBtn = btn;
        }
        [weekScrView addSubview:btn];
        [self.topButtonsArr addObject:btn];
    }
    UIButton *calendarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    calendarBtn.frame = CGRectMake(CGRectGetWidth(weekScrView.frame), 0, calendarWidth, 90*SCALEUNIT);
    [calendarBtn setImage:[UIImage imageNamed:@"TeachSignerCalenderImage"] forState:UIControlStateNormal];
    [calendarBtn addTarget:self action:@selector(calendarOpen:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:calendarBtn];
    return view;
}
- (NSMutableArray *)topButtonsArr{
    if (!_topButtonsArr) {
        _topButtonsArr = [[NSMutableArray alloc] init];
    }
    return _topButtonsArr;
}

#pragma mark ==========左侧视图==========
- (UIView *)returnLeftBtn{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20*SCALEUNIT, CGRectGetMaxY(self.topView.frame)+20*SCALEUNIT, 90*SCALEUNIT, CGRectGetHeight(self.frame)-CGRectGetHeight(self.topView.frame)-20*SCALEUNIT*3)];
    view.backgroundColor = [UIColor whiteColor];
    for (int i=0; i<2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, CGRectGetHeight(view.frame)/2.0*i, 90*SCALEUNIT, CGRectGetHeight(view.frame)/2.0);
        [btn setTitle:i==0?[NSString stringWithFormat:@"科\n二"]:[NSString stringWithFormat:@"科\n三"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"#686868"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithHexString:@"#21d4a4"] forState:UIControlStateSelected];
        [btn.titleLabel setNumberOfLines:2];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:LoginFont-2]];
        btn.showsTouchWhenHighlighted=YES;
        btn.tag = 20000+i;
        [btn addTarget:self action:@selector(touchChange:) forControlEvents:UIControlEventTouchUpInside];
        if (i==0) {
            btn.selected = !btn.selected;
            self.leftSelectBtn = btn;
        }
        [view addSubview:btn];
    }
    return view;
}

#pragma mark ==========中间展示视图==========
- (UIImageView *)noDataImgView{
    if (!_noDataImgView) {
        CGFloat wid = 179*2*SCALEUNIT;
        CGFloat hei = 140*2*SCALEUNIT;
        _noDataImgView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetWidth(self.frame)*0.5+(CGRectGetMaxX(self.leftView.frame)+20*SCALEUNIT)*0.5-wid*0.5, CGRectGetHeight(self.frame)*0.5+CGRectGetMinY(self.leftView.frame)*0.5-hei*0.5, wid, hei)];
        _noDataImgView.image = [UIImage imageNamed:@"CoachNoDataImg"];
        _noDataImgView.hidden = YES;
    }
    return _noDataImgView;
}
- (UIView *)headerView{//330+170+100
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 80*SCALEUNIT)];
        _headerView.backgroundColor = [UIColor whiteColor];
        UILabel *trainTime = [[UILabel alloc]initWithFrame:CGRectMake(35*SCALEUNIT, 0, 350*SCALEUNIT, CGRectGetHeight(_headerView.frame))];
        trainTime.font = [UIFont systemFontOfSize:LoginFont-3];
        trainTime.textColor = [UIColor colorWithHexString:@"#686868"];
        trainTime.textAlignment = NSTextAlignmentCenter;
        trainTime.text = @"训练时间";
        [_headerView addSubview:trainTime];
        
        UILabel *trainerNum = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(trainTime.frame), 0, 170*SCALEUNIT, CGRectGetHeight(_headerView.frame))];
        trainerNum.font = [UIFont systemFontOfSize:LoginFont-3];
        trainerNum.textColor = [UIColor colorWithHexString:@"#686868"];
        trainerNum.textAlignment = NSTextAlignmentCenter;
        trainerNum.text = @"训练人数";
        [_headerView addSubview:trainerNum];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(CGRectGetMaxX(trainerNum.frame), 0, CGRectGetWidth(_headerView.frame)-CGRectGetMaxX(trainerNum.frame), CGRectGetHeight(_headerView.frame));
        [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        btn.tag = 30000;
        [btn addTarget:self action:@selector(touchChange:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:btn];
    }
    return _headerView;
}
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.leftView.frame)+20*SCALEUNIT, CGRectGetMinY(self.leftView.frame), CGRectGetWidth(self.frame)-CGRectGetMaxX(self.leftView.frame)-20*SCALEUNIT*2, CGRectGetHeight(self.frame)-CGRectGetHeight(self.topView.frame)-20*SCALEUNIT*3) style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0, 50*SCALEUNIT, 0, 50*SCALEUNIT)];
        [_tableView setSeparatorColor:[UIColor colorWithHexString:@"#eeeeee"]];
        [_tableView registerClass:[TeachBottomCell class] forCellReuseIdentifier:@"TeachBottomCell"];
    }
    return _tableView;
}

#pragma mark ==========UITableView代理方法==========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105*SCALEUNIT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TeachBottomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachBottomCell" forIndexPath:indexPath];
    if (self.dataArr.count != 0) cell.dic = [self.dataArr objectAtIndex:indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TeachBottomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateToSingerVCWithIds:WithSubjectType:WithCurrentDate:)]) {
        [self.delegate teachBottomViewDelegateToSingerVCWithIds:[NSNumber numberWithLong:[[cell.dic objectForKey:@"id"] longLongValue]] WithSubjectType:[NSNumber numberWithInteger:self.selectSubject] WithCurrentDate:self.selectTime];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 80*SCALEUNIT;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return self.headerView;
}

#pragma mark ==========顶部+左侧按钮点击刷新方法==========
- (void)touchChange:(UIButton *)btn{
    if (btn.tag>=10000&&btn.tag<20000) {//顶部视图
        if (self.topSelectBtn == btn) {
            return;
        }
        [self.topSelectBtn setBackgroundColor:[UIColor whiteColor]];
        [self.topSelectBtn setTitleColor:[UIColor colorWithHexString:@"#686868"] forState:UIControlStateNormal];
        [btn setBackgroundColor:[UIColor colorWithHexString:@"#21d4a4"]];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.topSelectBtn = btn;
        self.selectTime = [[[self.timeArr objectAtIndex:btn.tag-10000] componentsSeparatedByString:@"\n"] firstObject];
        [self loadData];
    } else if (btn.tag>=20000&&btn.tag<30000) {//左侧视图
        if (self.leftSelectBtn == btn) {
            return;
        }
        self.leftSelectBtn.selected = !self.leftSelectBtn.selected;
        btn.selected = !btn.selected;
        self.leftSelectBtn = btn;
        self.selectSubject = btn.tag-20000==0?2:3;
        [self loadData];
    } else if (btn.tag==30000) {//中间刷新按钮
        
    } else {}
}

#pragma mark ==========跳转日历界面==========
- (void)calendarOpen:(UIButton *)btn{
    btn.userInteractionEnabled = NO;
    if ([self.delegate respondsToSelector:@selector(teachBottomViewDelegateToVCWithJudge:)]) {
        if (btn.userInteractionEnabled == NO) {
            btn.userInteractionEnabled = YES;
        }
        [self.delegate teachBottomViewDelegateToVCWithJudge:2];
    }
}

#pragma mark ==========手动改变时间列表==========
- (void)changeTimeWithDate:(NSDate *)selectDate{
    self.timeArr = nil;
    self.timeArr = [self getPriousorLaterDateFromDate:selectDate];
    for (int i=0; i<self.topButtonsArr.count; i++) {
        UIButton *btn = [self.topButtonsArr objectAtIndex:i];
        [btn setTitle:[self.timeArr objectAtIndex:i] forState:UIControlStateNormal];
        if (i==0) {
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor colorWithHexString:@"#21d4a4"]];
            self.topSelectBtn = btn;
        } else{
            [btn setTitleColor:[UIColor colorWithHexString:@"#686868"] forState:UIControlStateNormal];
            [btn setBackgroundColor:[UIColor whiteColor]];
        }
    }
    UIScrollView *weekSrcView = [self.topView viewWithTag:10000];
    [weekSrcView setContentOffset:CGPointMake(0, 0)];
    self.selectTime = [[[self.timeArr objectAtIndex:0] componentsSeparatedByString:@"\n"] firstObject];
    [self loadData];
}

#pragma mark ==========获取后几天时间==========
-(NSMutableArray *)getPriousorLaterDateFromDate:(NSDate *)selectDate{
    NSMutableArray *temArr = [[NSMutableArray alloc] init];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeInterval oneDay = 24*60*60*1;  //1天的长度
    for (int i=0; i<7; i++) {
        NSDateComponents *cmps = [calendar components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[[NSDate alloc]initWithTimeInterval:oneDay*i sinceDate:selectDate]];
        NSString *currentTimeString = [NSString stringWithFormat:@"%zd-%02zd-%02zd", cmps.year, cmps.month, cmps.day];
        [temArr addObject:[NSString stringWithFormat:@"%@\n    %@",currentTimeString,[BCMHelper weekdayStringFromDate:[[NSDate alloc] initWithTimeInterval:oneDay*i sinceDate:selectDate]]]];
    }
    return temArr;
}





@end
